package com.vaadin.tutorial.crm.backend.service;

import com.vaadin.tutorial.crm.backend.entity.SysUser;
import com.vaadin.tutorial.crm.backend.entity.Teacher;
import com.vaadin.tutorial.crm.backend.repository.SysUserRepository;
import com.vaadin.tutorial.crm.backend.util.CommonVar;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @Description:
 * @Author: Fan
 * @Date: 2021/1/18 20:32
 * @Version 1.0
 */
@Service
public class SysUserService implements UserDetailsService {
    private static final Logger LOGGER = Logger.getLogger(SysUserService.class.getName());

    private SysUserRepository userRepository;

    public SysUserService(SysUserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public SysUser getUserByUsername(String username){
        return userRepository.getUserByUsername(username);
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
         SysUser sysUser = userRepository.getUserByUsername(username);
         if (sysUser == null){
             throw new UsernameNotFoundException("用户不存在！");
         }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        authorities.add(new SimpleGrantedAuthority(sysUser.getUserRole()));
        return new org.springframework.security.core.userdetails.User(sysUser.getUsername(), sysUser.getPassword(),
                authorities);
    }

    /**
     * 查询所有用户信息
     * @return
     */
    public List<SysUser> findAll() {
        return userRepository.findAll();
    }

    /**
     * 根据用户名查询用户信息
     * @param userName
     * @return
     */
    public List<SysUser> findAll(String userName) {
        if (null == userName) {
            return userRepository.findAll();
        } else {
            return userRepository.search(userName);
        }
    }

    /**
     * 统计用户总数
     * @return
     */
    public long count() {
        return userRepository.count();
    }

    /**
     * 删除用户
     * @param sysUser
     */
    public void delete(SysUser sysUser) {
        userRepository.delete(sysUser);
    }

    /**
     * 新增用户
     * @param sysUser
     */
    public void save(SysUser sysUser) {
        if (sysUser == null) {
            LOGGER.log(Level.SEVERE, CommonVar.SAVE_NULL);
            return;
        }
        sysUser.setPassword(new BCryptPasswordEncoder().encode(sysUser.getPassword()));
        userRepository.save(sysUser);
    }
}
